package com.demo.blog.service;

import com.demo.blog.model.Captcha;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22652
 * Date: 2024-08-01
 * Time: 14:19
 */
@Service
public class CaptchaService {

    private final static long session_valid_timeout = 60 * 1000;

    @Autowired
    private Captcha captchaProperties;

    public Boolean check(String inputCode, HttpSession session) {

        //验证码生成的内容, 和用户输入的进行比较
        if (!StringUtils.hasLength(inputCode)) {
            return false;
        }
        //从session获取信息
        String savedCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if (inputCode.equalsIgnoreCase(savedCode)) {
            //判断验证码是否过期
            if (saveDate != null && System.currentTimeMillis() - saveDate.getTime() < session_valid_timeout) {
                return true;
            }
        }

        return false;
    }
}
